package wikitools.model;

import java.util.List;

import wikitools.model.exception.WrongResultSizeException;

import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.ext.DatabaseClosedException;
import com.db4o.ext.DatabaseReadOnlyException;
import com.db4o.query.Predicate;

/**
 * CRUD(Create, Read, Update, Delete) operations to database.
 * @author visus
 *
 */
public class DBUtil {
	
	
	/**
	 * Check an object's existence in database and then 
	 * store it in it. If it exists already, do nothing.
	 * @param <T>
	 * @param obj
	 * @param db
	 * @throws DatabaseClosedException
	 * @throws DatabaseReadOnlyException
	 */
	public static <T> void storeWithCheck(T obj, ObjectContainer db) throws DatabaseClosedException, DatabaseReadOnlyException{
		ObjectSet<T> response = db.queryByExample(obj);
		if(response.size()>0){ //if object already exists.
			return;
		}else{
			db.store(obj);
			return;
		}
	}
	
//	public static <T> void updateWithCheck(T obj, ObjectContainer db) throws DatabaseClosedException, DatabaseReadOnlyException{
//		
//		ObjectSet<T> response = db.queryByExample(obj);
//		if(response.size()>0){ //if object already exists. update it
//			return;
//		}else{
//			db.store(obj); //if not exist, something wrong happend.
//			return;
//		}
//	}
	
	
	public static <T extends Idable> T getByID(String id, ObjectContainer db) throws DatabaseClosedException, WrongResultSizeException{
		List<T> ret = db.query(new Predicate<T>() {
			
			private static final long serialVersionUID = 1L;

			public boolean match(T candidate) {
				return candidate.getId().equals("zhaop");
			}
		});
		
		if(ret.size()!=1){
			throw new WrongResultSizeException("Only one result should be returned.");
		}
		return ret.get(0);
	}
	
	public static void main(String[] args) {
		
	}
}


